var token;
var signModel;
var apiList = {};
apiList['api-000'] = {
	uri: '/api/actuator/health?details=true',
	method: 'GET',
	data: {}
};
apiList['api-001'] = {
	uri: '/api/current_user',
	method: 'GET',
	data: {}
};
apiList['api-002'] = {
	uri: '/api/serviceExporter/module/list?details=true',
	method: 'GET',
	data: {}
};
apiList['api-003'] = {
	uri: '/api/serviceExporter/route/list',
	method: 'GET',
	data: {}
};

apiList['api-004'] = {
	uri: '/api/serviceExporter/schedule/list',
	method: 'GET',
	data: {}
};

apiList['api-005'] = {
	uri: '/api/svc/user/list',
	method: 'POST',
	data: {
		"pageNo": 1,
		"pageSize": 5,
		"orderBy": {
			"field": "id",
			"sortType": "DESC"
		},
		"example": {
			"enabled": true
		}
	}
};

apiList['api-006'] = {
	uri: '/api/actionlog/list',
	method: 'POST',
	data: {
		"pageNo": 1,
		"pageSize": 5,
		"example": {}
	}
};

apiList['api-007'] = {
		uri: '/api/svc/user/add',
		method: 'POST',
		data: {
			"id": 1,
			"name": "user001",
			"mobile": "13800138000",
			"password": "123456"
		}
	};

apiList['api-008'] = {
	uri: '/api/svc/user/delete',
	method: 'POST',
	data: {
		"id": 1
	}
};

$(function() {
	if (!token) token = getCookies('userToken');
	if (token) {
		ajax('/api/current_user', 'GET', {}, function(data) {});
		$("#login_panel").hide();
		$("#logout_panel").show();
	} else {
		$("#login_panel").show();
		$("#logout_panel").hide();
	}
});

//setInterval(function() {
//    $('#timestamp').val(new Date().getTime());
//}, 1000);


function setCookies(name, value, expireDays) {
	expireDays = expireDays || 1;
	var exp = new Date();
	exp.setTime(exp.getTime() + expireDays * 24 * 60 * 60 * 1000);
	document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

function getCookies(name) {
	var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
	if (arr = document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}


function ajax(url, type, params, successCall) {

	console.log('url==>' + url);
	var postJSONString;
	if (type === 'POST') {
		postJSONString = JSON.stringify(params);
		console.log('postJSON==>' + postJSONString);
	}
	var headers = {
		"Authorization": token
	};
	if(signModel && url.indexOf('/api/open/signature') == -1){
		if($('#sign').val() === '' || $('#timestamp').val() === ''){
			alert('请先生成签名');
			return;
		}
		headers['x-open-clientId'] = $('#clientId').val();
		headers['x-open-sign'] = $('#sign').val();
		headers['timestamp'] = $('#timestamp').val();
	}
	
	$.ajax({
		headers: headers,
		dataType: "json",
		type: type,
		url: url,
		contentType: "application/json",
		//crossDomain: true,
		data: postJSONString,
		success: function(data) {
			console.log('=====>>>resp:',data);
			if (!data.code) {
				successCall(data);
				return;
			}
			if (data.code == 200) {
				successCall(data.data);
			}else {
				successCall(data);
			}
			if (data.code == 401) {
				token = null;
				setCookies("userToken", "", 0);
				setTimeout(function(){
					$("#login_panel").show();
					$("#logout_panel").hide();
				},200);
				return;
			}
		},
		error: function(xhr, type) {
			alert('系统错误:' + JSON.stringify(xhr));
		}
	});
}

$('#methodKey').change(function(){
	var api = apiList[$(this).val()];
	console.log('api',api)
	$('#apiParams').text(api.data.length == 0 ? '' : JSON.stringify(api.data));
	$('#response_previve').text('');
});

$('#open_sign_btn').click(function(){
	signModel = $(this).is(':checked');
	if(signModel){
		$('#sign_panel').show();
	}else{
		$('#sign_panel').hide();
	}
});

$('#act_login_btn').click(function() {
	var params = {};
	params.account = $('#account').val();
	params.password = $('#password').val();

	ajax('/api/login', 'POST', params, function(res) {
		//$('#response_previve').text(formatJson);
		token = res.sessionId;
		setCookies("userToken", token, 1);
		console.log('token==>>' + token);
		window.location.reload();

	});
});

$('#logout_btn').click(function() {
   
	ajax('/api/logout', 'POST', {}, function(res) {
		token = null;
		setCookies("userToken", "", 0);
		setTimeout(function(){
			$("#login_panel").show();
			$("#logout_panel").hide();
		},200);
	});

});

$('#gen_sign_btn').click(function(){
	var api = apiList[$('#methodKey').val()];
	var clientId = $("#clientId").val();
	ajax('/api/open/signature?clientId='+clientId, 'POST', api.data, function(res) {
		$("#timestamp").val(res.timestamp);
		$("#sign").val(res.sign);
	});
});

$('#test_api_btn').click(function() {
    
	var api = apiList[$('#methodKey').val()];

	ajax(api.uri, api.method, api.data, function(res) {
		var formatJson = pettyJson(JSON.stringify(res));
		$('#response_previve').text(formatJson);
	});

});




function pettyJson(json) {
	var formatted = '', //转换后的json字符串
		padIdx = 0, //换行后是否增减PADDING的标识
		PADDING = '    '; //4个空格符
	if (typeof json !== 'string') {
		json = JSON.stringify(json);
	}
	json = json.replace(/([\{\}])/g, '\r\n$1\r\n')
		.replace(/([\[\]])/g, '\r\n$1\r\n')
		.replace(/(\,)/g, '$1\r\n')
		.replace(/(\r\n\r\n)/g, '\r\n')
		.replace(/\r\n\,/g, ',');
	(json.split('\r\n')).forEach(function(node, index) {
		var indent = 0,
			padding = '';
		if (node.match(/\{$/) || node.match(/\[$/)) indent = 1;
		else if (node.match(/\}/) || node.match(/\]/)) padIdx = padIdx !== 0 ? --padIdx : padIdx;
		else indent = 0;
		for (var i = 0; i < padIdx; i++) padding += PADDING;
		formatted += padding + node + '\r\n';
		padIdx += indent;
	});
	return formatted;
}
